package com.example.project.projectspringcloud.common.email;

import com.example.project.projectspringcloud.entity.sys.SysConfig;
import com.example.project.projectspringcloud.service.sys.SysConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Map;
import java.util.Properties;

/**
 * 邮件
 */
@Component
public class EmailComponent extends JavaMailSenderImpl {

    private final Logger logger = LoggerFactory.getLogger(EmailComponent.class);

    @Autowired
    private SysConfigService sysConfigService;

    public EmailComponent conf() throws Exception {
        Map emailConfig = sysConfigService.configs(new SysConfig("email"));
        try {
            super.setHost((String) emailConfig.get("host"));
            super.setPort(Integer.parseInt((String) emailConfig.get("port")));
            super.setUsername((String) emailConfig.get("username"));
            super.setPassword((String) emailConfig.get("password"));
        } catch (NullPointerException | ClassCastException e) {
            logger.error("系统邮箱配置异常!", e);
            throw new Exception("系统邮箱配置异常!");
        }

        return this;
    }

    public EmailComponent make(String title, String content, String target) throws Exception {
        Properties properties = new Properties();
        properties.put("mail.smtp.auth", false);
        super.setJavaMailProperties(properties);

        MimeMessage mimeMessage = super.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
        mimeMessageHelper.setFrom(new InternetAddress(super.getUsername()));
        mimeMessageHelper.setSubject(title);
        mimeMessageHelper.setText(content, true);
        mimeMessageHelper.setTo(new InternetAddress(target));
        mimeMessage = mimeMessageHelper.getMimeMessage();
        this.send(mimeMessage);

        return this;
    }

    @Override
    public void send(SimpleMailMessage... simpleMessages) throws MailException {
        super.send(simpleMessages);
    }
}
